package com.weishuang.monitor.leader.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.Page;
import com.weishuang.monitor.leader.commons.entity.Result;
import com.weishuang.monitor.leader.commons.enums.SCODE;
import com.weishuang.monitor.leader.commons.utils.ResultUtils;
import com.weishuang.monitor.leader.entity.SysRole;
import com.weishuang.monitor.leader.entity.dto.RoleDTO;
import com.weishuang.monitor.leader.entity.vo.RoleVO;
import com.weishuang.monitor.leader.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 角色信息 前端控制器
 * </p>
 *
 * @author weishuang
 * @since 2021-03-23
 */
@RestController
@RequestMapping("/leader/sysRole")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 分页查询角色列表
     * @param page
     * @return
     */
    @GetMapping("page")
    public Result getRolePage(RoleDTO page) {
        Page<SysRole> result = sysRoleService.getRolePage(page);
        return ResultUtils.success(result);
    }

    /**
     * 新增
     * @param sysRole
     * @return
     */
    @PostMapping
    public Result addRole(@Validated SysRole sysRole) {
        sysRole.setId(IdWorker.getIdStr());
        sysRole.insertInit();
        sysRoleService.save(sysRole);
        return ResultUtils.success();
    }

    /**
     * 修改
     * @param id
     * @param sysRole
     * @return
     */
    @PutMapping("/{id}")
    public Result updateRole(@PathVariable String id, @Validated SysRole sysRole) {
        sysRole.setId(id);
        sysRole.updateInit();
        sysRoleService.updateById(sysRole);
        return ResultUtils.success();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteRole(@PathVariable String id) {
        LambdaUpdateWrapper<SysRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysRole::getIsDefault, SCODE.NO_CODE.getValue());
        updateWrapper.eq(SysRole::getId, id);
        SysRole sysRole = new SysRole();
        sysRole.deleteInit();
        sysRoleService.update(sysRole,updateWrapper);
        return ResultUtils.success();
    }

    /**
     * 查询角色列表与用户已勾选的角色
     * @param userId
     * @return
     */
    @GetMapping("listRoleAndCheckRoleByUserId/{userId}")
    public Result listRoleAndCheckRoleByUserId(@PathVariable String userId) {
        List<RoleVO> sysRoleList = sysRoleService.listRoleAndCheckRoleByUserId(userId);
        return ResultUtils.success(sysRoleList);
    }

}
